import React, {Component,} from 'react'
import {Link, withRouter} from 'react-router-dom'
import {Icon} from "antd-mobile";
import {connect,} from 'react-redux'
import ShareIcon from "../../../../../res/images/web/shared/share-icon.png"
import StarIcon from "../../../../../res/images/web/game-room/like@2x.png"
import StarClickedIcon from "../../../../../res/images/web/game-room/收藏点亮@2x.png"
import './HeaderTitle.css'
import {formatDate, formatScheduleDate} from "../../../../../utils/dateService";
import LocalStorageService from "../../../../../utils/LocalStorageService";
import {GameDataArrayToObject, GameDataObjectFinalized} from "../../../../../redux/game";
import {goBack} from "../../../../../utils/goback";
import {behaviorReq} from "../../../../../apis/goApis";
import {GlobalStore} from "../../../../../context";



class HeaderTitle extends Component {

    constructor(props) {
        super(props)
        this.matchId = this.props.match.params.gameId
        this.storage = LocalStorageService
        this.date = this.props.history.location.state && this.props.history.location.state.date
        this.state = {
            // statusId: 0,
            gameEnded: false,
            gameMarked: false,
        }
    }

    componentDidMount() {

        // let time = this.props.currentGame.info.matchtime
        // let date = formatDate(new Date(time * 1000))
        let isLogin = (this.storage.get('isLogin'))
        if (isLogin) {
            if (this.props.history.location.state) {
                let date = this.props.history.location.state.date
                let games = this.props.game.games[date]
                if (games) {
                    let matches = games.matches
                    if (matches.length === 0) {
                        this.props.doFetchGameListAll({date})
                    }
                } else {
                    this.props.doFetchGameListAll({date})
                }
                this.getMarkList()
            }
        }


        // let markList = this.props.game.markList
        //
        // if (markList.length === 0) {
        //     const uid = this.storage.get('userid')
        //     this.props.doFetchMarkList({
        //         uid,
        //     })
        // } else {
        //     let markListDate = markList.find(dateList => dateList[0] === date)
        //     let matchId = this.matchId
        //     let i = markListDate.findIndex(id => id === matchId)
        //     console.log(i)
        //     if (i > -1) {
        //         this.setState({
        //             gameMarked: true,
        //         })
        //     }
        // }

    }

    componentDidUpdate(prevProps, prevState, snapshot) {

        const prevId = prevProps.currentGame.info.statusid
        const statusid = this.props.currentGame.info.statusid
        const prevMark = prevProps.game.markList
        const mark = this.props.game.markList
        const isLogin = LocalStorageService.get('isLogin')

        if (isLogin) {


            if (prevId !== statusid) {


                if (statusid >= 8) {
                    this.setState({
                        gameEnded: true,
                    })
                } else {
                    this.getMarkList()
                }

            }

            if (prevMark !== mark) {

                this.getMarkList()
            }

        }



    }

    getMarkList = () => {
        let markList = this.props.game.markList
        let matchTime = this.props.game.currentGame.info.matchtime
        let date = formatDate(new Date(matchTime * 1000))
        // let date = this.props.history.location.state.date

        if (markList.length === 0) {
            const uid = this.storage.get('userid')
            const userDetail = this.props.user.userdetail
            if (userDetail.initFlag === 0) {
                return
            } else {
                this.props.doFetchMarkList({
                    uid,
                })
            }
        } else {
            let markListDate = markList.find(dateList => dateList[0] === date)
            let matchId = this.matchId
            let i = markListDate && markListDate.findIndex(id => id === matchId)
            if (i === -1) {
                this.setState({
                    gameMarked: false,
                })
            }
            if (i > -1) {
                this.setState({
                    gameMarked: true,
                })
            }
        }
    }

    getFollows = () => {
        const fs = 'follow_games'
        const storage = LocalStorageService
        const follows = storage.get(fs)
        return follows
    }

    markGame = (matchid,) => {
        let login = this.storage.get('isLogin')
        if (login) {
            let del = this.state.gameMarked
            let matchTime = this.props.game.currentGame.info.matchtime
            behaviorReq({
                userid: LocalStorageService.get('userid'),
                handle: '足球关注',
            })
            let date = formatDate(new Date(matchTime * 1000))
            let uid = this.storage.get('userid')
            this.props.doMarkGame({
                matchid,
                uid,
                del,
                date,
            })
            this.markGameInStorage()
        } else {
            this.props.history.push('../login')
        }
    }

    markGameInStorage = () => {
        const storage = LocalStorageService
        let time = this.props.currentGame.info.matchtime
        let date = formatDate(new Date(time * 1000))
        let dateGames = this.props.game.games[date]
        // console.log(dateGame)
        let {teams, events, stages, matches,} = dateGames
        let i = matches.findIndex(match => match[0] === Number(this.matchId))
        let gameArr = matches[i]
        if (gameArr) {
            const gameObjInit = GameDataArrayToObject(gameArr)
            const gameObjFinal = GameDataObjectFinalized(gameObjInit, teams, events, stages)
            storage.markOneGame(this.matchId, date, gameObjFinal)
        }
        // if (follows) {
        //     let dateFollow = follows[date]
        //     if (dateFollow) {
        //         let isFollowed = dateFollow.findIndex(obj => obj.matchId === Number(this.matchId))
        //         if (isFollowed === -1) {
        //             follows[date].push(gameObjFinal)
        //         } else {
        //             follows[date].splice(isFollowed, 1)
        //         }
        //         storage.save(fs, follows)
        //     } else {
        //         follows[date] = [gameObjFinal]
        //         storage.save(fs, follows)
        //     }
        //     // this.setState({gameMarked: !this.state.gameMarked})
        // } else {
        //     let follows = {}
        //     follows[date] = [gameObjFinal]
        //     storage.save(fs, follows)
        // }
    }

    goBack = () => {
        const ps = this.context.gamePagePosition.positions
        ps[0] = 0
        this.context.gamePagePosition.setPagePosition(ps)
        this.props.history.goBack()
    }

    render() {
        const {
            history,
            currentGame,
            showShare,
            atTop,
        } = this.props


        // const leave = () => {
        //     // goBack(history)
        //     const search = this.props.location.search
        //     const pushState = this.props.location.state
        //     if (search === '') {
        //
        //         if (pushState.from === 'ai-order') {
        //             goBack(history)
        //             // history.go(-3)
        //         } else {
        //             goBack(history)
        //         }
        //         // if (pushState.from) {
        //         //     history.go(-2)
        //         // } else {
        //         //     goBack(history)
        //         // }
        //
        //     } else {
        //         goBack(history, '../game')
        //     }
        // }

        const matchEvent = currentGame.matchevent.name_zh
        const statAtTime = currentGame.info.matchtime * 1000
        const statusId = currentGame.info.statusid

        let delay = statusId > 8 && statusId < 999
        let statusText

        if (delay) statusText = '比赛推迟'

        // const startAtTimeObj = new Date(statAtTime)
        const scheduleTimeObj = new Date(statAtTime)
        const scheduleDateString = formatDate(scheduleTimeObj)
        let scheduleDateFormat = scheduleDateString.slice(0, 4) + '年' + scheduleDateString.slice(4, 6) + '月' + scheduleDateString.slice(6) + '日'
        const scheduleTimeString = formatScheduleDate(scheduleTimeObj)
        const scheduleTime = scheduleDateFormat + ' ' + scheduleTimeString
        const canFollow = this.state.gameEnded || !atTop
        const ShareIconTemplate = (<img
            onClick={showShare}
            src={ShareIcon}
            alt=''
            style={{marginRight: '1rem',}}
        />)

        const FollowIconTemplate = (<img
            style={{
                height: '28px',
                width: '28px',
            }}
            src={this.state.gameMarked ? StarClickedIcon : StarIcon}
            onClick={() => this.markGame(this.matchId)}
            alt=''
        />)

        const middle = <div className='game-room-header-title-category'>
            <p>
                {matchEvent.length > 0 ? matchEvent : matchEvent}
            </p>
            {delay
                ? <p>{statusText}</p>
                : <p>
                    {statAtTime > 0 ? scheduleTime : null}
                </p>
            }

        </div>


        const titleTemplate = (
            <div
                className='game-room-header-title'
                style={{
                    top: atTop ? '' : '50%',
                    transform: atTop ? '' : 'translateY(-50%)',
                }}
            >
                {/*<Link*/}
                {/*    to={'../game'}*/}
                {/*    // onClick={leave}*/}
                {/*>*/}
                {/*    <Icon*/}
                {/*        type='left'*/}
                {/*        color='#fff'*/}
                {/*        size='lg'*/}
                {/*    />*/}
                {/*</Link>*/}

                <Icon
                    type='left'
                    color='#fff'
                    size='lg'
                    onClick={() => this.goBack()}
                />

                {atTop ? middle : null}


                <div>
                    {atTop ? ShareIconTemplate : null}
                    {/*{this.state.gameEnded || !isLogin ? null : FollowIconTemplate}*/}
                    {canFollow ? null : FollowIconTemplate}
                </div>
            </div>

        )

        return titleTemplate
    }
}


const mapState = state => ({
    currentGame: state.game.currentGame,
    game: state.game,
    user: state.user,
})

const mapDispatch = dispatch => ({
    doFetchGameListAll: (payload) => dispatch.game.doFetchGameListAll(payload),
    doFetchMarkList: (payload) => dispatch.game.doFetchMarkList(payload),
    doMarkGame: (payload) => dispatch.game.doMarkGame(payload),
})

HeaderTitle.contextType = GlobalStore


export default connect(mapState, mapDispatch)(withRouter(HeaderTitle))
